#! /usr/bin/env python
# tovid.py

"""Frontend to the tovid suite.
"""

usage = """Usage:

    tovid [command] [arguments ...]

Where 'command' is one of the following:

    Command     Description                                 Formerly
    -----------------------------------------------------------------
    id          Identify one or more video files            idvid
    dvd         Author and/or burn a DVD                    makedvd
    menu        Create an MPEG menu                         makemenu
    vcd         Author and/or burn a VCD                    makevcd
    xml         Create (S)VCD or DVD .xml file              makexml
    postproc    Post-process an MPEG video file             postproc
    disc        Create a DVD with menus                     todisc
    gui         Start the tovid GUI                         todiscgui
    mpg         Encode videos to MPEG format                tovid
    titlesets   Start the titleset wizard                   (new)

Run 'tovid <command>' with no further arguments to get help on a command,
and what arguments it expects.
"""

import sys
import os
import subprocess
import time

# Command names to script mappings
_scripts = {
    'id': 'idvid',
    'dvd': 'makedvd',
    'menu': 'makemenu',
    #'?': 'makemenugui',
    'vcd': 'makevcd',
    'xml': 'makexml',
    'postproc': 'postproc',
    'disc': 'todisc',
    'gui': 'todiscgui',
    'mpg': 'makempg',
    'batch': 'tovid-batch',
    'titlesets': 'make_titlesets',
}

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print(usage)
        sys.exit()
    else:
        args = sys.argv[1:]

    # Determine actual installation path to tovid's executables
    # (Assumes the 'tovid' in the user's path is a symbolic link
    # to the true installation directory)
    actual_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
    # Prepend the actual install path to the $PATH environment variable
    os.environ['PATH'] = actual_dir + os.pathsep + os.environ['PATH']

    command = args.pop(0)

    if command in ['-prefix', '--prefix']:
        print actual_dir
        sys.exit(0)

    print("tovid executables assumed to be in '%s'" % actual_dir)

    if command in _scripts:
        script = _scripts[command]
        # Ensure that the script exists in actual_dir
        # (Should never happen if installer is configured correctly)
        script_path = os.path.join(actual_dir, script)
        if not os.path.exists(script_path):
            print("DEBUG: Missing script: '%s'" % script)
            sys.exit(1)
        else:
            try:
                status = subprocess.call([script] + args)
            except KeyboardInterrupt:
                print("\n!!! tovid was manually interrupted. Exiting.")
                # Sleep a second to let the script clean up
                time.sleep(1)
                sys.exit(1)
            else:
                sys.exit(status)
    else:
        print(usage)
        print("Unknown command: '%s'" % command)
        sys.exit(1)

